package controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.mybeans.form.FormBeanFactory;

import databean.Email;
import databean.User;
import formbean.ReplyForm;

import model.EmailDAO;
import model.Model;

public class ReplyAction  extends Action {
	
	private FormBeanFactory<ReplyForm> formBeanFactory = FormBeanFactory.getInstance(ReplyForm.class);
	
	private EmailDAO	emailDAO;

	public ReplyAction(Model model) {
		emailDAO = model.getEmailDAO();
	}

	public String getName() { return "reply.do"; }

	public String perform(HttpServletRequest request,HttpServletResponse response) {
		
		HttpSession session = request.getSession();
		List<String> errors = new ArrayList<String>();
		request.setAttribute("errors",errors);
		
		try {	        
			if (session.getAttribute("user") == null) {
				return "user-login.do";
			}      
			request.setAttribute("user",(User) request.getSession(false).getAttribute("user"));
			User user = (User) request.getSession(false).getAttribute("user");	
			ArrayList<Email> newConversationIDs = emailDAO.getConversationIDs(user.getUserID());
	        request.removeAttribute("conversationIDs");
	        request.setAttribute("conversationIDs",newConversationIDs);
	    	
	    	ReplyForm form = formBeanFactory.create(request);
			request.setAttribute("form",form);
			
	        if (!form.isPresent()) {	        	
	            return "conversation-feed.jsp";
	        }
	        
	        // Any validation errors?
	        errors.addAll(form.getValidationErrors());
	        if (errors.size() != 0) {
	            return "conversation-feed.jsp";
	        }
	        
			String emailContent = form.getReplyMessage();
			String conversationID = request.getParameter("conversationID");	
			
			if(conversationID == null){
				Long temp=newConversationIDs.get(0).getConversationID();
				System.out.println(temp);
				conversationID = String.valueOf(temp);
			}
			
	    	ArrayList<Email> newEmails = emailDAO.getEmailsByConversationID(Long.parseLong(conversationID), user.getUserID());	
	    	request.setAttribute("emails",newEmails);
			
	        String subj=null;
	        String recip=null;
	        if(newEmails.size()!=0){
	        	Email email = newEmails.get(0);	
	        	recip=email.getRecipient();
	        	if(user.getEmail().equals(recip))
	        		recip=email.getSender();
	        	subj = email.getSubject();
	        }
						
			String format = "MM-dd-yyyy HH:mm:ss";
			TimeZone localZone = TimeZone.getDefault();
			String time = null;
			Calendar cal = Calendar.getInstance();
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			time= sdf.format(cal.getTime());
			
			Email email = new Email();
			email.setUserID(user.getUserID());
			email.setOutlookID(user.getEmail());
			email.setTimestamp(time+" "+localZone.getDisplayName());
			email.setSubject(subj);
			email.setSender(user.getEmail());
			email.setRecipient(recip);			
			email.setBody(emailContent);
			email.setStatus(form.getStatus());
			email.setConversationID(EmailDAO.retrieveConversationID(email));
			emailDAO.createEmail(email);
			newEmails = emailDAO.getEmailsByConversationID(Long.parseLong(conversationID), user.getUserID());	
			request.setAttribute("emails",newEmails);
			
			String webapp = request.getContextPath();
			return webapp + "/conversation-feed.do";

		} catch (Exception e) {
        	errors.add(e.getMessage());
        	return "user-error-list.jsp";
        }	
	}
}
